package io.renren.modules.generator.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.ExcelUtil;
import io.renren.constant.DeviceFinal;
import io.renren.modules.generator.dao.DeviceSiteDao;
import io.renren.modules.generator.entity.DeviceSiteEntity;
import io.renren.modules.generator.service.DeviceSiteService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.renren.modules.generator.entity.DeviceHourEntity;
import io.renren.modules.generator.service.DeviceHourService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2020-09-07 14:14:46
 */
@RestController
@RequestMapping("generator/devicehour")
@Api("接口")
public class DeviceHourController {
    @Autowired
    private DeviceHourService deviceHourService;
    @Autowired(
            required = false
    )
    protected HttpServletRequest request;
    @Autowired(
            required = false
    )
    protected HttpServletResponse response;

    @Autowired
    private DeviceSiteDao deviceSiteDao;


    /**
     * 按小时查询各个设备的指标
     * @param deviceCodes 设备编码组
     * @param time 需要查询的时间
     * @return
     */
    @RequestMapping("/quota")
    @ApiOperation("分页列表")
    public R quota(
            @RequestParam("deviceCodes") String[] deviceCodes,
            @RequestParam("time") String time
    ){
        return R.ok().put("data", deviceHourService.quota(deviceCodes,time));
    }

    /**
     * 列表
     */
    @RequestMapping("/export")
    @ApiOperation("分页列表")
    @ResponseBody
    public void export(@RequestParam Map<String, Object> params){
        try {
            List<DeviceHourEntity> deviceHourEntityList = deviceHourService.selectDeviceHourEntityListByParams(params);

            XSSFWorkbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("来源用户信息");

            Row row = sheet.createRow(0);

            CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 5);
            sheet.addMergedRegion(cellRangeAddress);
            row.createCell(0).setCellValue("备注：指标数据根据条件导出");

            row = sheet.createRow(1);
            row.createCell(0).setCellValue("所属设备");
            row.createCell(1).setCellValue("地点");
            row.createCell(2).setCellValue("指标值");
            row.createCell(3).setCellValue("指标名称与单位");
            row.createCell(4).setCellValue("指标产生时间");

            int i = 2;

            if (Objects.nonNull(deviceHourEntityList) && deviceHourEntityList.size() > 0) {
                QueryWrapper<DeviceSiteEntity> deviceSiteWrapper;

                Date date = new Date();
                //可以转成你想要的格式 yyyy/MM/dd HH:mm:ss 等等
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                List<DeviceSiteEntity> deviceSiteEntityList = deviceSiteDao.selectByMap(new HashMap<String, Object>());
                Map<String, DeviceSiteEntity> map = new HashMap<>();
                if (Objects.nonNull(deviceSiteEntityList)) {
                    for (int j = 0; j < deviceSiteEntityList.size(); j++) {
                        map.put(deviceSiteEntityList.get(j).getDeviceCode(), deviceSiteEntityList.get(j));
                    }
                }
                DeviceSiteEntity deviceSiteEntity;
                for (int j = 0; j < deviceHourEntityList.size(); j++) {
                    row = sheet.createRow(i + j);
                    deviceSiteEntity = map.get(deviceHourEntityList.get(j).getDeviceEncrypt());
                    ExcelUtil.setCellValue(row, 0, DeviceFinal.devictTypeMap.get(deviceSiteEntity.getDeviceType()));
                    ExcelUtil.setCellValue(row, 1, deviceSiteEntity.getSiteName());
                    ExcelUtil.setCellValue(row, 2, deviceHourEntityList.get(j).getDeviceValue());
                    ExcelUtil.setCellValue(row, 3, deviceHourEntityList.get(j).getDeviceIndexName());
                    ExcelUtil.setCellValue(row, 4, format.format(deviceHourEntityList.get(j).getCreateTime()));
                }
            }

//            response.setContentType("application/octet-stream;charset=ISO8859-1");
//            response.setHeader("Content-Disposition", "attachment;filename=data.xls");
//            response.addHeader("Pargam", "no-cache");
//            response.addHeader("Cache-Control", "no-cache");
            this.response.setContentType("application/octet-stream;charset=ISO8859-1");
            this.response.setHeader("Content-disposition", "attachment;filename=data.xls");
            this.response.addHeader("Pargam", "no-cache");
            this.response.addHeader("Cache-Control", "no-cache");
            ServletOutputStream out = this.response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @ApiOperation("分页列表")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = deviceHourService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{deviceCodeTime}")
    @ApiOperation("根据id获取实体")
    public R info(@PathVariable("deviceCodeTime") String deviceCodeTime){
		DeviceHourEntity deviceHour = deviceHourService.getById(deviceCodeTime);

        return R.ok().put("deviceHour", deviceHour);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @ApiOperation("保存")
    public R save(@RequestBody DeviceHourEntity deviceHour){
		deviceHourService.save(deviceHour);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @ApiOperation("更新")
    public R update(@RequestBody DeviceHourEntity deviceHour){
		deviceHourService.updateById(deviceHour);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ApiOperation("删除")
    public R delete(@RequestBody String[] deviceCodeTimes){
		deviceHourService.removeByIds(Arrays.asList(deviceCodeTimes));

        return R.ok();
    }

}
